#include "topKFrequent.h"
std::vector<int> topKFrequent(std::vector<int> &nums, int k) {
    std::unordered_map<int, int> cache;
    std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
    std::vector<int> res;
    // 统计数字出现频率
    for (auto e : nums) {
        if (cache.count(e)) {
            cache[e] += 1;
        } else {
            cache[e] = 1;
        }
    }
    for (auto e : cache) {
        if (minHeap.size() >= k) {
            if (e.second >= cache[minHeap.top()]) {
                minHeap.pop();
                minHeap.push(e.first);
            } else {
                continue;
            }

        } else {
            minHeap.push(e.first);
        }
    }
    while (minHeap.empty()) {
        res.push_back(minHeap.top());
        minHeap.pop();
    }
    return res;
}
